package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return
     */
    public List<AddressBook> list() {
        List<AddressBook> addressBookList = addressBookMapper.list(BaseContext.getCurrentId());

        return addressBookList;
    }

    /**
     * 新增地址
     *
     * @param addressBook
     */
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());

        addressBookMapper.add(addressBook);
    }

    /**
     * 设置默认地址
     *
     * @param id
     */
    public void setDefault(Long id) {
        AddressBook nowDefault = addressBookMapper.getDefault(1);
        if (nowDefault != null) {
            nowDefault.setIsDefault(0);
            addressBookMapper.update(nowDefault);
        }

        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    /**
     * 根据id修改地址
     * @param addressBook
     */
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);

    }

    /**
     * 查询默认地址
     * @return
     */
    public AddressBook getDefault() {
         int id = 1;
        AddressBook aDefault = addressBookMapper.getDefault(id);

        return aDefault;
    }

    /**
     * 根据id删除地址
     * @param id
     */
    public void del(Long id) {
        addressBookMapper.del(id);
    }
}
